import axios from 'axios'
import cancelFetch from './cancelFetch'
import store from '@/store/index'
import router from '@/router/index'
import utils from "@/utils/index"

import {
    ElLoading,
    ElMessageBox,
} from 'element-plus';

const fetch = axios.create({
    baseURL: import.meta.env.MODE == 'development' ? '/release' : '/',
    // timeout: 500 // 请求超时时间
    timeout: 60000 * 2 // 请求超时时间
});

let loading = null
fetch.interceptors.request.use(
    config => {
        if (config.withLoading) {
            loading = ElLoading.service()
        }

        cancelFetch.removePending(config)
        cancelFetch.addPending(config)

        // 让每个请求携带自定义token
        let userInfo = utils.getlocalStorage("userInfo") || {}
        config.headers['X-Token'] = userInfo.sessionid

        if (config.url.indexOf('logout') > -1) {
            config.headers['X-Token'] = ''
        }

        return config
    },
    error => {
        return Promise.reject(error);
    }
)

fetch.interceptors.response.use(
    ({ status, data, config }) => {
        if (status == 200) {
            // debugger
            if (data.code == 200) {
                if (config.withLoading) {
                    setTimeout(() => {
                        loading.close()
                    }, 200);
                }
                return Promise.resolve(data)
            }
        }
        // debugger
        let msg = data.msg || '响应失败'
        ElMessageBox.alert(msg)

        return Promise.reject(msg);
    },
    error => {
        // console.log(error);
        // console.log(error.request);
        // console.log(error.response);
        // console.log(error.message);

        // var originalRequest = error.config;
        // if (error.code == 'ECONNABORTED' && error.message.indexOf('timeout') != -1 && !originalRequest._retry) {
        //     originalRequest._retry = true
        //     return fetch.request(originalRequest);
        // }
        if (error && error.config && error.config.withLoading) {
            setTimeout(() => {
                loading.close()
            }, 200);
        }

        if (error && error.response && error.response.status === 401) {
            // 执行退出逻辑
            ElMessageBox.alert('身份过期，请重新登录','警告')
            store.dispatch("logout");
        } else {
            ElMessageBox.alert('网络连接错误，请稍后再试','警告')
        }
        return Promise.reject(error);
    }
)
export default fetch
